package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AddressController {
    @Autowired
    private AddressService addressService;
    //http://localhost:8081/addressBook/default
    @GetMapping("/addressBook/default")
    public ResultInfo findDefault(){
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault,1);
        Address address = addressService.getOne(wrapper);
        if (address!=null){
            return ResultInfo.success(address);
        }else {
            return ResultInfo.error("没有默认地址");
        }
    }
    @PutMapping("/addressBook/default")
    public ResultInfo updatemoren(@RequestBody Map<String,Long> map){
        Long id = map.get("id");
        addressService.updatemoren(id);
        return ResultInfo.success(null);
    }
    //http://localhost:8081/addressBook
    @PostMapping("/addressBook")
    public ResultInfo save(@RequestBody Address address){
        address.setUserId(UserHolder.get().getId());
        addressService.save(address);
        return ResultInfo.success(null);
    }
    //http://localhost:8081/addressBook/list
    @GetMapping("/addressBook/list")
    public ResultInfo list(){
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addressList = addressService.list(wrapper);
        return ResultInfo.success(addressList);
    }
}
